import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from '@/stores/user';

// 创建 axios 实例
const axiosInstance = axios.create({
    baseURL: "http://localhost:18675/", // 网关地址
    timeout: 10000, // 设置请求超时时间 10s
});

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config) => {
        const userStore = useUserStore();
        const token = userStore.userinfo.token;

        // 调试信息
        console.log('获取到的 token:', token);

        if (token) {
            config.headers["Authorization"] = `Bearer ${token}`;
        } else {
            console.log('token 不存在，无法设置 Authorization 头');
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
    (response) => {
        if (!response.data.isSuc) {
            ElMessage.error(response.data.msg);
            return Promise.reject(new Error(response.data.msg));
        }
        return response.data;
    },
    (error) => {
        const { response, message } = error;
        if (response) {
            switch (response.status) {
                case 401:
                    sessionStorage.removeItem("token");
                    ElMessage.error("请先登录");
                    window.location.href = "/"; // 跳转到登录页面
                    break;
                default:
                    console.error(`请求错误：${response.status}`);
                    ElMessage.error(`请求错误：${response.status}`);
            }
        } else {
            ElMessage.error("网络连接异常" + message);
        }
        return Promise.reject(error);
    }
);

// 导出 axios 实例
export default axiosInstance;